<template>
  <a-drawer v-model:visible="visible" class="custom-class" title="全局配置-转场设置" placement="right" width="800"
    :maskClosable="false">
    <a-tabs v-model:activeKey="activeTab" type="card" @change="changeTab">
      <a-tab-pane :key="1" tab="智能匹配">
        <p style="color: rgb(115 122 135)">为视频混剪组合智能匹配转场</p>
      </a-tab-pane>
      <a-tab-pane :key="2" tab="自定义">
        <div class="custom-secendTab">
          <a-tabs v-model:activeKey="customSecendTabActiveKey" @change="changeCustomSecendTab">
            <a-tab-pane v-for="item in transList" :key="item.id" :tab="item.name">
              <div class="custom-list">
                <div class="custom-item" v-for="ele in item.materials" :key="ele.id" @click="toggleItem(ele)">
                  <template v-if="ele.material_type == 'video'">
                    <video :class="{
                      'custom-item-active': isSelected(ele.scene_type),
                    }" class="custom-item-img" :src="ele.material_url" name="media" id="videoPlayer"
                      @mouseenter="playVideo" @mouseleave="pauseVideo" />
                  </template>
                  <template v-else-if="ele.material_type == 'image'">
                    <img :class="{
                      'custom-item-active': isSelected(ele.scene_type),
                    }" class="custom-item-img" :src="ele.material_url" />
                  </template>

                  <span style="font-size: 12px; color: rgba(28, 31, 35, 0.8)">{{
                    ele.material_name
                  }}</span>
                  <a-checkbox class="checkbox" v-if="isSelected(ele.scene_type)" :checked="isSelected(ele.scene_type)"
                    @change="toggleItem(ele)"></a-checkbox>
                </div>
              </div>
              <a-row type="flex" style="align-items: center; margin-top: 15px">
                <a-col :span="3"> 转场动画时长 </a-col>
                <a-col>
                  <a-input-number v-model:value="duration" addon-after="秒" id="inputNumber" :min="0.1" :max="0.8"
                    :step="0.1"></a-input-number>
                </a-col>
              </a-row>
              <a-row type="flex" style="align-items: center; margin-top: 15px">
                <a-col :span="3"> 匹配方式 </a-col>
                <a-radio-group v-model:value="transition_config.global">
                  <a-radio :value="0">每组镜头组随机匹配一个转场</a-radio>
                  <a-radio :value="1">所有镜头组随机相同的转场</a-radio>
                </a-radio-group>
              </a-row>
            </a-tab-pane>
            <template #rightExtra>
              <a-button type="text" size="small">已选择{{ itemSelectData }}</a-button>
              <a-button type="link" size="small" @click="toggleChecked('add')">全选</a-button>

              <a-button type="link" size="small" @click="toggleChecked('del')"
                v-show="itemSelectData >= 1">全部取消</a-button>
            </template>
          </a-tabs>
        </div>
      </a-tab-pane>
    </a-tabs>
    <template #footer>
      <a-row type="flex" justify="end">
        <a-button style="margin-right: 8px" type="primary" @click="onClose('submit')">确认添加</a-button>
        <a-button @click="onClose('close')">取消</a-button>
      </a-row>
    </template>
  </a-drawer>
</template>
<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  onMounted,
  ref,
} from "vue";
import {
  QuestionCircleOutlined,
  UploadOutlined,
  CloudUploadOutlined,
  CaretRightOutlined,
  CloseOutlined,
} from "@ant-design/icons-vue";
import request from "@/common/utils/request";
import { useStore } from "vuex";
import { message } from "ant-design-vue";
export default defineComponent({
  components: {
    QuestionCircleOutlined,
    UploadOutlined,
    CloudUploadOutlined,
    CaretRightOutlined,
    CloseOutlined,
  },

  setup() {
    const state = reactive({
      visible: false,
      activeTab: 1,
      customSecendTabActiveKey: 0,
      currentPlaying: null,
    });
    const store = useStore();
    // 获取仓库中的数据
    const VideoMashup = computed(() => {
      return store.state.videoMixCut.VideoMashup;
    });
    // 复制的转场数据
    const transition_config = ref({});
    const duration = ref(0);
    onMounted(() => {
      // 获取转场数据
      getTransData();
    });
    // 获取转场列表
    const transList = ref([]);
    // 打开 复制转场数据
    const showDrawer = () => {
      state.visible = true; //打开弹窗
      transition_config.value = JSON.parse(
        JSON.stringify(VideoMashup.value.transition_config)
      ); //初始化转场数据
      duration.value = transition_config.value?.duration / 1000; //初始化转场动画时长
      if (transition_config.value.type == 0) {
        state.activeTab = 1;
      } else {
        state.activeTab = transition_config.value.type;
      }
    };
    const getTransData = async () => {
      const res = await request.get(
        "/work_ai",
        "/user/shotstack/material/clip/transition/list"
      );
      console.log(res, "转场数据");
      transList.value = res.result;
      if (transList.value.length > 0) {
        state.customSecendTabActiveKey = transList.value[0].id;
      }
    };
    // 当前高亮项的data
    const targetData = computed(() => {
      return (
        transList.value.find(
          (ele) => ele.id == state.customSecendTabActiveKey
        ) || []
      );
    });
    // 每一项的被选择条数
    const itemSelectData = computed(() => {
      // 每一项的转场名称
      let scene_typeArr = transition_config.value.transitions.map(
        (item) => item.transition_name
      );
      console.log(scene_typeArr, "所有的选中的数据字符串");
      if (!!targetData.value && scene_typeArr.length > 0) {
        const selectNum = targetData.value.materials.filter((ele) =>
          scene_typeArr.includes(ele.scene_type)
        ).length;
        return selectNum;
      } else {
        return 0;
      }
    });
    // 每一项的总条数
    const itemTotalData = computed(() => {
      if (!!targetData.value) {
        return targetData.value.materials.length;
      } else {
        return 0;
      }
    });
    const toggleChecked = (type) => {
      // 找到当前所在项
      if (type == "add") {
        // 全部要添加的项
        const addArr = targetData.value.materials.map((ele) => {
          return {
            name: ele.material_name,
            transition_name: ele.scene_type,
            transition_duration: duration.value,
            transition_type: targetData.value.scene_type,
            transition_selector: ele.type,
          };
        });
        // 全部勾选
        const newtransitionArr = [
          ...transition_config.value.transitions,
          ...addArr,
        ].reduce((prev, next) => {
          if (prev.length) {
            const index = prev.findIndex(
              (item) => item.transition_name === next.transition_name
            );
            if (index == -1) {
              prev.push(next);
            }
            return prev;
          } else {
            return [next];
          }
        }, []);
        console.log(newtransitionArr, "全部勾选去重的结果");
        transition_config.value.transitions = newtransitionArr;
      } else {
        const delArr = targetData.value.materials.map(
          (ele) => ele.material_name
        );
        // 反选删除
        transition_config.value.transitions =
          transition_config.value.transitions.filter((ele) => {
            return !delArr.includes(ele.name);
          });
      }
    };

    // 提交或关闭弹窗
    const onClose = (type) => {
      console.log(transition_config.value.type, state.activeTab);
      console.log(duration.value, "转场提交数据");
      if (type == "submit") {
        if (
          state.activeTab == 2 &&
          transition_config.value.transitions.length == 0
        ) {
          message.error("请选择转场方式");
          return;
        }
        // 保存到仓库, 如果切换为智能匹配则将时长设置为800
        if (state.activeTab == 1) {
          transition_config.value.duration = 800;
          transition_config.value.transitions =
            transition_config.value.transitions.map((ele) => {
              return {
                ...ele,
                transition_duration: 800,
              };
            });
        } else if (state.activeTab == 2) {
          transition_config.value.duration = duration.value * 1000;
          transition_config.value.transitions =
            transition_config.value.transitions.map((ele) => {
              return {
                ...ele,
                transition_duration: duration.value * 1000,
              };
            });
        }
        transition_config.value.type = state.activeTab;
        store.dispatch("videoMixCut/SetVideoMashupItem", {
          key: "transition_config",
          value: transition_config.value,
        });
      }
      console.log(transition_config.value);
      state.visible = false;
    };
    const changeTab = (e) => {
      state.activeTab = e;
      console.log(transition_config.value.type);
    };
    // 修改当前高亮的转场项
    const changeCustomSecendTab = (e) => {
      state.customSecendTabActiveKey = e;
    };

    // 勾选某项
    const toggleItem = (data) => {
      const targetIndex = transition_config.value.transitions.findIndex(
        (value) => {
          return value.name == data.material_name;
        }
      );
      if (targetIndex !== -1) {
        transition_config.value.transitions.splice(targetIndex, 1);
      } else {
        transition_config.value.transitions.push({
          name: data.material_name,
          transition_name: data.scene_type,
          transition_duration: duration.value,
          transition_type: targetData.value.scene_type,
          transition_selector: data.type,
        });
      }
    };
    // 判断是否被勾选
    const isSelected = (scene_type) => {
      let scene_typeArr = transition_config.value.transitions.map(
        (item) => item.transition_name
      );
      return scene_typeArr.includes(scene_type);
    };
    // 鼠标移入
    const playVideo = (event) => {
      // 如果有正在播放的视频，先将其重置
      if (state.currentPlaying) {
        state.currentPlaying.pause();
        state.currentPlaying.currentTime = 0; // 回退到视频的起始点
      }
      // 播放当前视频
      event.target.currentTime = 2
      event.target.play();
      // 更新当前播放的视频
      state.currentPlaying = event.target;
    };
    const pauseVideo = (event) => {
      // 只有当鼠标移出当前播放的视频时才暂停
      if (state.currentPlaying && event.target === state.currentPlaying) {
        state.currentPlaying.pause();
      }
    };
    return {
      ...toRefs(state),
      showDrawer,
      onClose,
      changeTab,
      changeCustomSecendTab,
      toggleChecked,
      toggleItem,
      isSelected,
      getTransData,
      transList,
      store,
      transition_config,
      targetData,
      itemSelectData,
      itemTotalData,
      duration,
      playVideo,
      pauseVideo,
    };
  },
});
</script>
<style lang="less" scoped>
.custom-secendTab {
  padding: 10px;

  .custom-list {
    display: grid;
    margin-top: 13px;
    max-height: 540px;
    min-height: 82px;
    grid-gap: 12px;
    grid-template-columns: repeat(5, 1fr);
    overflow-y: scroll;
    border: 1px solid #ededee;
    padding: 20px;

    .custom-item {
      align-items: center;
      display: flex;
      flex-direction: column;
      position: relative;
      box-sizing: border-box;

    }

    .custom-item-img {
      border: 2px solid transparent;
      border-radius: 3px;
      box-sizing: border-box;
      cursor: pointer;
      height: 68px;
      object-fit: cover;
      width: 100%;
    }

    .checkbox {
      position: absolute;
      top: -4px;
      left: 0;
    }

    .custom-item-active {
      border: 2px solid #2878ff;
    }
  }
}
</style>
